<template>
  <div class="app-container">
    <!--      集群管理-->
    <!--      顶部操作栏-->
    <div class="filter-container">
      <el-button
        v-waves
        v-has="hasbuttons.addnode"
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        style="margin-bottom: 10px"
        @click="createNodeOpen"
      >
        创建集群
      </el-button>
      <el-button
        v-waves
        v-has="hasbuttons.editnode"
        :disabled="currentNode.name == null"
        class="filter-item"
        style="margin-left: 10px; margin-bottom: 10px"
        type="primary"
        icon="el-icon-edit"
        @click="updateNodeOpen"
      >
        修改当前集群
      </el-button>

      <el-button
        slot="reference"
        v-waves
        v-has="hasbuttons.deletenode"
        :disabled="currentNode.name == null"
        class="filter-item"
        style="margin-left: 10px; margin-bottom: 10px"
        type="primary"
        icon="el-icon-delete"
        @click="deleteNode"
      >
        删除当前集群
      </el-button>
    </div>
    <div
      v-loading="listLoading"
      :style="{ height: dynamicHeight }"
      class="pane-class"
    >
      <split-pane
        max-height="500"
        :min-percent="splitMinPrecent"
        :default-percent="defaultPercent"
        split="vertical"
        style="border: 1px solid #e8e8e8"
      >
        <!--左侧集群列表-->
        <template slot="paneL">
          <el-container style="max-height: 800px">
            <el-main style="padding-top: 0px">
              <span v-if="!openSide">
                <section-title
                  title=""
                  open-class="el-icon-caret-right"
                  @changePaneL="changePaneLWith"
                />
              </span>
              <span v-else>
                <section-title
                  title="集群列表"
                  open-class="el-icon-caret-left"
                  @changePaneL="changePaneLWith"
                />
                <node-list
                  :data-source="dataSource"
                  node-key="oid"
                  :default-props="defaultProps"
                  @change="clickNode"
                ></node-list>
              </span>
            </el-main>
          </el-container>
        </template>
        <!--              右侧节点详情-->
        <template slot="paneR">
          <!--                <section-title title="集群数据" />-->
          <el-container style="max-height: 100%">
            <el-main style="padding: 0px">
              <node-detail
                :node-info="currentNode"
                @delete="deleteMachine"
                @change="createMachineOpen"
                @update="updateMachineOpen"
              ></node-detail>
            </el-main>
          </el-container>
        </template>
      </split-pane>
    </div>
    <!--新建集群模态框-->
    <div class="dia">
      <el-dialog :close-on-click-modal="false" :visible.sync="createModel">
        <template slot="title">
          <div class="titleZise">
            <svg-icon icon-class="cluster-monitor-add" />
            <span>新建集群</span>
          </div>
        </template>
        <el-form
          ref="createNodeForm"
          :model="form"
          :rules="rules"
          label-width="auto"
        >
          <el-form-item label="集群名称" prop="name">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="createModel = false">取 消</el-button>
          <el-button type="primary" @click="createNode">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--修改集群模态框-->
    <div class="dia">
      <el-dialog :close-on-click-modal="false" :visible.sync="updateModel">
        <template slot="title">
          <div class="titleZise">
            <svg-icon icon-class="cluster-monitor-add" />
            <span>修改集群</span>
          </div>
        </template>
        <el-form
          ref="updateNodeForm"
          :model="form"
          :rules="rules"
          label-width="auto"
        >
          <el-form-item label="集群名称" prop="name">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="updateModel = false">取 消</el-button>
          <el-button type="primary" @click="updateNode">确 定</el-button>
        </div>
      </el-dialog>
    </div>

    <!--新增机器模态框-->
    <div class="dia">
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="createMachineModel"
      >
        <template slot="title">
          <div class="titleZise">
            <svg-icon icon-class="machine-add" />
            <span>新增机器</span>
          </div>
        </template>
        <el-form
          ref="createMachineForm"
          :model="form"
          :rules="rules"
          label-width="auto"
        >
          <el-form-item label="集群名称">
            <el-input
              v-model="currentNode.name"
              disabled
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="机器名称" prop="name">
            <el-input v-model="form.name" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="机器IP" prop="ip">
            <el-input v-model="form.ip" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="createMachineModel = false">取 消</el-button>
          <el-button type="primary" @click="createMachine">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <!--修改机器模态框-->
    <div class="dia">
      <el-dialog
        :close-on-click-modal="false"
        :visible.sync="updateMachineModel"
      >
        <template slot="title">
          <div class="titleZise">
            <svg-icon icon-class="machine-add" />
            <span>修改机器</span>
          </div>
        </template>
        <el-form
          ref="updateMachineForm"
          :model="currentMachine"
          :rules="rules"
          label-width="auto"
        >
          <el-form-item label="集群名称">
            <el-input
              v-model="currentNode.name"
              disabled
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="机器名称" prop="name">
            <el-input
              v-model="currentMachine.name"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item label="机器IP" prop="ip">
            <el-input v-model="currentMachine.ip" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="currentMachine.description"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="updateMachineModel = false">取 消</el-button>
          <el-button type="primary" @click="updateMachine">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
  import splitPane from 'vue-splitpane' //可拖动长度表格
  import sectionTitle from '@/components/SectionTitle' //表头
  import { deleteAction, getAction, postAction, putAction } from '@/api/action'
  import { BaseListMixin } from '@/mixins/BaseListMixin'
  import NodeList from '@/views/cluster-monitor/compoents/NodeList' //节点列表
  import NodeDetail from '@/views/cluster-monitor/compoents/NodeDetail'
  const hasbuttons = {
    addnode: 'clusterMonitor:ClusterNodeManage:addnode',
    editnode: 'clusterMonitor:ClusterNodeManage:editnode',
    deletenode: 'clusterMonitor:ClusterNodeManage:delnode',
  }
  export default {
    name: 'ClusterNodeManage',
    components: { NodeDetail, NodeList, splitPane, sectionTitle },
    mixins: [BaseListMixin],
    data() {
      //自定义校验规则
      //不能为空
      var blankSpace = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'))
        }
        if (value.length > 64) {
          return callback(new Error('名称超过最大长度限制'))
        }
        callback()
      }
      //校验ip地址
      var isIP = (rule, value, callback) => {
        var reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
        if (!reg.test(value)) {
          return callback(new Error('请输入正确IP地址！'))
        }
        callback()
      }
      return {
        hasbuttons: hasbuttons,
        splitMinPrecent: 12,
        defaultPercent: 30,
        dataSource: [],
        listLoading: false,
        openSide: true,
        filterText: '',
        currentCheckNodeData: {},
        activeName: 'first',
        defaultProps: {
          children: 'children',
          label: 'nodeName',
        },
        workFlowBaseInfo: {
          preId: '编号',
          name: '名称',
          category: '分类',
          createUser: '所有者',
        },
        modelIcon: {
          //模态框图标
          create: 'el-icon-document-add',
          update: 'el-icon-edit-outline',
        },
        url: {
          // list: '/presoftasim/wf/workflow/list',
          // detail: 'presoftasim/wf/workflow/detail',
          createNode: '/presoftasim/clusterManage/clusterManageNode/create',
          treeList: '/presoftasim/clusterManage/clusterManageNode/treeList',
          updtaeNode: '/presoftasim/clusterManage/clusterManageNode/update',
          deleteNode: '/presoftasim/clusterManage/clusterManageNode/delete',
          createMachine:
            '/presoftasim/clusterManage/clusterManageNodeMachine/create',
          updateMachine:
            '/presoftasim/clusterManage/clusterManageNodeMachine/update',
          deleteMachine:
            '/presoftasim/clusterManage/clusterManageNodeMachine/delete',
        },
        disableMixinCreated: true,
        form: {
          name: undefined,
          nodeId: undefined,
          createUserName: undefined,
        },
        rules: {
          name: [
            { validator: blankSpace, trigger: 'blur' },
            { required: true, trigger: 'blur' },
          ],
          ip: [
            { validator: blankSpace, trigger: 'blur' },
            { validator: isIP, trigger: 'blur' },
            { required: true, trigger: 'blur' },
          ],
        }, //校验规则
        createModel: false, //新建节点模态框是否打开
        updateModel: false, //修改节点模态框是否打开
        createMachineModel: false, //新增机器模态框是否打开
        updateMachineModel: false, //修改机器模态框是否打开
        currentNode: {}, //当前选中的节点
        currentMachine: {}, //当前选中的机器
      }
    },
    computed: {
      dynamicHeight: function () {
        // 40是box的margin-top和margin-bottom  35是页脚 footer高度
        return window.innerHeight > 710
          ? window.innerHeight - 40 - 35 + 'px'
          : '710px'
      },
    },
    created() {
      this.getList()
    },
    mounted() {},
    updated() {
      console.log('-------===============-----')
      console.log(this.$refs.flowUp)
    },
    methods: {
      // 模块title展示  最好调整到computed中
      changePaneLWith() {
        this.openSide = !this.openSide
        if (this.openSide) {
          this.splitMinPrecent = 12
          this.defaultPercent = 25
        } else {
          this.splitMinPrecent = (150 / window.innerWidth) * 30
          this.defaultPercent = (150 / window.innerWidth) * 30
        }
      },
      //获取节点列表
      getList() {
        this.listLoading = true
        getAction(this.url.treeList, this.form)
          .then((response) => {
            if (response.code === 200) {
              this.dataSource = response.data
              //更新当前节点数据
              if (this.currentNode.oid != null) {
                for (let i in this.dataSource) {
                  if (this.currentNode.oid == this.dataSource[i].oid) {
                    this.currentNode = this.dataSource[i]
                    break
                  }
                }
              } else {
                this.currentNode = this.dataSource[0]
              }
              this.listLoading = false
            } else {
              this.submitFail(response.message)
            }
          })
          .catch((err) => {
            console.log(err)
          })
      },
      getDetail(oid) {
        getAction(this.url.detail, { oid: oid }).then((res) => {})
      },

      // tab页面切换事件
      handleClick(tab, event) {},
      //nodeList组件中出发点击node事件
      clickNode(data) {
        this.currentNode = Object.assign({}, data)
      },
      reload() {
        this.isRouterAlive = false
        this.$nextTick(function () {
          this.isRouterAlive = true
        })
      },
      //打开新建节点模态框
      createNodeOpen: function () {
        this.form = {}
        this.createModel = true
      },
      //修改新建节点模态框
      updateNodeOpen: function () {
        this.form = this.currentNode
        this.updateModel = true
      },
      //打开新建机器模态框
      createMachineOpen: function (data) {
        this.form = {}
        this.form.nodeId = this.currentNode.oid
        this.createMachineModel = true
      },
      //打开修改机器模态框
      updateMachineOpen: function (data) {
        this.currentMachine = Object.assign({}, data)
        this.updateMachineModel = true
      },
      //新建节点
      createNode: function () {
        this.$refs['createNodeForm'].validate((valid) => {
          if (valid) {
            this.form.createUser = this.$store.state.user.id
            this.form.createUserName = this.$store.state.user.name
            postAction(this.url.createNode, this.form)
              .then((response) => {
                if (response.code === 200) {
                  this.submitOk(response.message)
                  this.getList()
                  this.createModel = false
                } else {
                  this.submitFail(response.message)
                }
              })
              .catch((err) => {
                console.log(err)
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      //修改节点
      updateNode: function () {
        this.$refs['updateNodeForm'].validate((valid) => {
          if (valid) {
            this.form.modifyUser = this.$store.state.user.id
            putAction(this.url.updtaeNode, this.form)
              .then((response) => {
                if (response.code === 200) {
                  this.submitOk(response.message)
                  this.getList()
                  this.updateModel = false
                } else {
                  this.submitFail(response.message)
                }
              })
              .catch((err) => {
                console.log(err)
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      //删除节点
      deleteNode: function () {
        var that = this
        this.$confirm('确定删除当前选中的集群?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            if (this.currentNode.machines.length == 0) {
              this.currentNode.modifyUser = this.$store.state.user.id
              deleteAction(this.url.deleteNode, this.currentNode)
                .then((response) => {
                  if (response.code === 200) {
                    this.submitOk(response.message)
                    this.getList()
                    this.currentNode = this.dataSource[0]
                  } else {
                    this.submitFail(response.message)
                  }
                })
                .catch((err) => {
                  console.log(err)
                })
            } else {
              this.submitFail('请清空该集群下机器！')
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除',
            })
          })
      },
      //新建机器
      createMachine: function () {
        this.$refs['createMachineForm'].validate((valid) => {
          if (valid) {
            this.form.createUser = this.$store.state.user.id
            this.form.createUserName = this.$store.state.user.name
            postAction(this.url.createMachine, this.form)
              .then((response) => {
                if (response.code === 200) {
                  this.submitOk(response.message)
                  this.getList()
                  this.createMachineModel = false
                } else {
                  this.submitFail(response.message)
                }
              })
              .catch((err) => {
                console.log(err)
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      //修改机器
      updateMachine: function () {
        this.$refs['updateMachineForm'].validate((valid) => {
          if (valid) {
            this.currentMachine.modifyUser = this.$store.state.user.id
            putAction(this.url.updateMachine, this.currentMachine)
              .then((response) => {
                if (response.code === 200) {
                  this.submitOk(response.message)
                  this.getList()
                  this.updateMachineModel = false
                } else {
                  this.submitFail(response.message)
                }
              })
              .catch((err) => {
                console.log(err)
              })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      //  删除机器
      deleteMachine: function (data) {
        this.currentMachine = data
        this.currentMachine.modifyUser = this.$store.state.user.id
        deleteAction(this.url.deleteMachine, this.currentMachine)
          .then((response) => {
            if (response.code === 200) {
              this.submitOk(response.message)
              this.getList()
            } else {
              this.submitFail(response.message)
            }
          })
          .catch((err) => {
            console.log(err)
          })
      },
    },
  }
</script>

<style lang="scss" scoped>
  .el-main {
    padding: 0px;
  }
</style>
